package com.chery.media.service

import android.app.Service
import android.content.Intent
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import com.blankj.utilcode.util.LogUtils
import com.chery.media.contacts.MusicType
import com.chery.media.network.model.MusicBean
import com.chery.media.network.model.MusicPlayBean
import com.chery.media.ui.play.playViewModel

class MusicPlayService : Service(), MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener,
    MediaPlayer.OnPreparedListener {

    // 音乐列表
    val musicList = arrayListOf<MusicBean>()

    // 音乐播放器
    var mMediaPlayer: MediaPlayer? = null

    // 当前播放的音乐位置
    var currentIndex = 0

    // 当前播放的音乐
    var music: MusicBean? = null

    // 缓冲状态
    var prepareStatus = false

    // 通过handler更新播放进度
    private val mHandler = Handler { msg ->
        if(music != null && mMediaPlayer != null && mMediaPlayer?.isPlaying == true){
            updateMusic()
        }
        true
    }

    /**
     * 设置音乐列表
     */
    fun setMusicList(list: ArrayList<MusicBean>, isAdd: Boolean = false) {
        if (isAdd.not()) musicList.clear()
        musicList.addAll(list)
        music = null
    }

    /**
     * 开始播放
     */
    fun startPlay() {
        LogUtils.eTag(this.javaClass.name, "index======${currentIndex}")
        LogUtils.eTag(this.javaClass.name, "musicList.size======${musicList.size}")
        if (currentIndex >= musicList.size) return
        music = musicList[currentIndex]
        mMediaPlayer?.reset()
        mMediaPlayer?.setDataSource(music?.playPath)
        mMediaPlayer?.prepare()
    }

    /**
     * 通过索引播放音乐
     */
    fun playMusicByIndex(index: Int = 0){
        LogUtils.eTag(this.javaClass.name, "index======${index}")
        currentIndex = index
        startPlay()
    }

    /**
     * 暂停播放
     */
    fun pausePlay() {
        mMediaPlayer?.pause()
    }

    /**
     * 继续播放
     */
    fun continuePlay() {
        mMediaPlayer?.start()
    }

    /**
     * 停止播放
     */
    fun stopPlay() {
        mMediaPlayer?.stop()
        mMediaPlayer?.reset()
    }

    /**
     * 重置播放器
     */
    fun resetPlay() {
        mMediaPlayer?.reset()
    }

    /**
     * 播放上一首
     */
    fun playPrevious() {
        currentIndex--
        if (currentIndex < 0) currentIndex = musicList.size - 1
        startPlay()
    }

    /**
     * 播放下一首
     */
    fun playNext() {
        currentIndex++
        if (currentIndex >= musicList.size) currentIndex = 0
        startPlay()
    }

    /**
     * 更新音乐进度
     */
    private fun updateMusic() {
        if (playViewModel.currentType.value == MusicType.USB) {
            playViewModel.currentUsbPlayMusic.value = MusicPlayBean(
                currentIndex,
                music?.author,
                music?.cover,
                music?.lyricPath,
                music?.title,
                "${getMusicCurrentTime()}",
                "${mMediaPlayer?.duration ?: 0}",
                mMediaPlayer?.isPlaying
            )
        } else {
            playViewModel.currentHotPlayMusic.value = MusicPlayBean(
                currentIndex,
                music?.author,
                music?.cover,
                music?.lyricPath,
                music?.title,
                "${getMusicCurrentTime()}",
                "${mMediaPlayer?.duration ?: 0}",
                mMediaPlayer?.isPlaying
            )
        }
        mHandler.sendEmptyMessageDelayed(0, 1000)
    }

    /**
     * 获取当前音乐播放进度
     */
    private fun getMusicCurrentTime(): Int {
        return mMediaPlayer?.currentPosition ?: 0
    }

    override fun onCreate() {
        mMediaPlayer = MediaPlayer()
        mMediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
        mMediaPlayer?.setOnCompletionListener(this)
        mMediaPlayer?.setOnErrorListener(this)
        mMediaPlayer?.setOnPreparedListener(this)
    }

    override fun onBind(intent: Intent?): IBinder {
        return MusicPlayBinder()
    }

    override fun onCompletion(mp: MediaPlayer?) {
        LogUtils.eTag(this.javaClass.simpleName, "onCompletion")
        playNext()
    }

    override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        return false
    }

    override fun onPrepared(mp: MediaPlayer?) {
        prepareStatus = true
        mp?.start()
        updateMusic()
    }

    inner class MusicPlayBinder : Binder() {

        fun getMusicPlayService(): MusicPlayService = this@MusicPlayService

    }
}